package com.jy.appmarket.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import com.android.corestat.service.WorkingService;
import com.jy.app.market.idata.data.LockscreenCfg;
import com.jy.app.market.idata.data.LockscreenCfgItem;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.GameBoxActivity;
import com.jy.appmarket.model.AppInfoModel;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.EssentialNetEngine;
import com.jy.appmarket.network.engine.LockscreenCfgEngine;
import com.jy.appmarket.network.engine.WidgetNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.WidgetCacheStrategy;
import com.jy.appmarket.network.resultdata.BaseResultData;
import com.jy.appmarket.network.resultdata.EssentialResultData;
import com.jy.appmarket.network.resultdata.LockscreenCfgResult;
import com.jy.appmarket.network.resultdata.WidgetResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.notification.AppUpdateNotification;
import com.jy.appmarket.screenlock.utils.DateUtils;
import com.jy.appmarket.screenlock.utils.LockScreenConfig;
import com.jy.appmarket.utils.AdManager;
import com.jy.appmarket.utils.AppUpdateTask;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.NetTools;
import com.jy.appmarket.utils.NetTools.NET_TYPE;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.utils.WidgetIconUtils;
import com.jy.appmarket.widget.essential.PhoneEssentialWidgetProvider;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.Log;

public class PollService extends Service implements NetTaskListener {

	private static final long TIME = 1000 * 60 * 60;
	private static final String TAG = "PollService";
	private static final int PHONE_ESSENTIAL = 1;

	private static final int TOOL_WIDGET = 2;
	private static final int GAME_WIDGET = 3;
	private static final int ENTERTAINMENT_WIDGET = 4;

	private static final int LOCKSCREEN_CFG = 5;

	private NetTask mPhoneEssentialTask;
	private NetTask mToolWidgetTask;
	private NetTask mGameWidgetTask;
	private NetTask mEntertainmentWidgetTask;
	private NetTask mLockscreenCfgTask;

	private boolean mPhoneEssentialRunning = false;
	private boolean mToolRunning = false;
	private boolean mGameRunning = false;
	private boolean mEntertainmentRunning = false;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		WidgetIconUtils.getInstance().initWidgetCacheFromAssetsIfNecessary(this);
	}

	private AppUpdateTask mUpdateTask;

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (!WorkingService.isServiceTaskFinished(this)) {
			if (!WorkingService.isServiceRunning(this)) {
				WorkingService.startWorkingService(this, 0);
			}
		}
		AdManager.instance(this).getAdFromNetwork(false);

		requestWidgetData();
		requestAppUpdate();
		// 如果有需要更新的app，根据条件发送通知
		AppUpdateNotification.showAppUpdateNotification(this);
		updateLockscreenConfig();
		createGameboxShortCut();
		return super.onStartCommand(intent, flags, startId);
	}

	private void createGameboxShortCut() {
		SharedPreferences sp = getSharedPreferences("gamebox", 0);
		int count = sp.getInt("count", 0);
		if (count > 5) {
			return;
		}
		if (DateUtils.isToday(sp.getLong("last_date", 0))) {
			return;
		}

		Intent addIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_gamebox);
		Intent myIntent = new Intent(Intent.ACTION_MAIN);
		myIntent.setComponent(new ComponentName(this, GameBoxActivity.class));
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "游戏盒子");
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);
		addIntent.putExtra("duplicate", false);
		sendBroadcast(addIntent);
		sp.edit().putInt("sc", count + 1).putLong("last_date", System.currentTimeMillis()).commit();
	}

	private void updateLockscreenConfig() {
		if (mLockscreenCfgTask != null && mLockscreenCfgTask.isTaskRunning()) {
			return;
		}
		LockscreenCfg cfg = LockScreenConfig.getLockscreenConfig(this);
		if (cfg != null && DateUtils.isSameDay(System.currentTimeMillis(), cfg.getTime())) {
			LogUtil.d(TAG, "lockscreen config already updated");
			return;
		}

		LockscreenCfgEngine engine = new LockscreenCfgEngine();
		mLockscreenCfgTask = new NetTask(this, engine, LOCKSCREEN_CFG);
		mLockscreenCfgTask.setListener(this);
		new Thread(mLockscreenCfgTask).start();
	}

	// 一天检测一次apk的更新，失败的话，一个小时重试一次
	private void requestAppUpdate() {
		if (mUpdateTask != null && mUpdateTask.isRunning()) {
			LogUtil.d(TAG, "appupdate is running");
			return;
		}
		long now = System.currentTimeMillis();
		if (now < Prefs.getAppUpdateNextQueryTime(this)) {
			LogUtil.d(TAG, "appupdate time not arrive");
			return;
		}

		String curr = new SimpleDateFormat("yyyy-MM-dd").format(now);

		if (curr.equals(Prefs.getRequestAppupdateTime(this))) {
			return;
		}

		mUpdateTask = new AppUpdateTask(this);
		mUpdateTask.execute(0);
	}

	private void requestWidgetData() {
		if (!mPhoneEssentialRunning) {
			mPhoneEssentialRunning = true;
			EssentialNetEngine engine = new EssentialNetEngine(this);
			mPhoneEssentialTask = new NetTask(this, engine, PHONE_ESSENTIAL);
			mPhoneEssentialTask.setListener(this);
			new Thread(mPhoneEssentialTask).start();
		}
		if (!mToolRunning) {
			mToolRunning = true;
			WidgetNetEngine engine = new WidgetNetEngine(WidgetNetEngine.TYPE_TOOL);
			mToolWidgetTask = new NetTask(this, engine, TOOL_WIDGET);
			mToolWidgetTask.setListener(this);
			new Thread(mToolWidgetTask).start();
		}
		if (!mGameRunning) {
			mGameRunning = true;
			WidgetNetEngine engine = new WidgetNetEngine(WidgetNetEngine.TYPE_GAME);
			mGameWidgetTask = new NetTask(this, engine, GAME_WIDGET);
			mGameWidgetTask.setListener(this);
			new Thread(mGameWidgetTask).start();
		}

		if (!mEntertainmentRunning) {
			mEntertainmentRunning = true;
			WidgetNetEngine engine = new WidgetNetEngine(WidgetNetEngine.TYPE_ENTERTAINMENT);
			mEntertainmentWidgetTask = new NetTask(this, engine, ENTERTAINMENT_WIDGET);
			mEntertainmentWidgetTask.setListener(this);
			new Thread(mEntertainmentWidgetTask).start();
		}
	}

	private void updateWidgetIcon(List<AppInfoModel> recList, int type, boolean isNew) {
		WidgetIconUtils utils = WidgetIconUtils.getInstance();
		List<AppInfoModel> recommends = utils.trimRecommends(this, recList);
		String[] user = utils.getUserSavedPackages(this, type);
		List<AppInfoModel> list = utils.mergeWidgetList(this, recommends, user);
		boolean showNew = false;
		if (isNew) {
			switch (type) {
			case WidgetIconUtils.TYPE_TOOL_WIDGET:
				Prefs.setEnterToolWidget(this, false);
				break;
			case WidgetIconUtils.TYPE_GAME_WIDGET:
				Prefs.setEnterGameWidget(this, false);
				break;
			case WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET:
				Prefs.setEnterEntertainmentWidget(this, false);
				break;
			}
		}

		switch (type) {
		case WidgetIconUtils.TYPE_TOOL_WIDGET:
			showNew = !Prefs.hasEnterToolWidget(this);
			break;
		case WidgetIconUtils.TYPE_GAME_WIDGET:
			showNew = !Prefs.hasEnterGameWidget(this);
			break;
		case WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET:
			showNew = !Prefs.hasEnterEntertainmentWidget(this);
			break;

		}
		utils.updateIcon(this, list, type, showNew);
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		BaseResultData result = engine.getResultData();

		if (tag == PHONE_ESSENTIAL) {
			mPhoneEssentialRunning = false;

			EssentialResultData necessaries = (EssentialResultData) result;
			if (!necessaries.isCacheVaild()) {
				Prefs.setEnterNecessariesWidget(this, false);
			}
			Intent it = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			AppWidgetManager am = AppWidgetManager.getInstance(this);
			ComponentName cn = new ComponentName(this, PhoneEssentialWidgetProvider.class);
			int[] ids = am.getAppWidgetIds(cn);
			if (ids != null && ids.length != 0) {
				Bundle extra = new Bundle();
				extra.putIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
				it.setComponent(cn);
				it.putExtras(extra);
				sendBroadcast(it);
			} else {
				LogUtil.i(TAG, "no widget to update necessaries");
			}
		} else if (tag == LOCKSCREEN_CFG) {
			LockscreenCfgResult lsresult = (LockscreenCfgResult) result;
			if (lsresult == null) {
				return;
			}

			LockscreenCfg cfg = lsresult.getConfig();

			if (cfg == null) {
				cfg = new LockscreenCfg();
			}
			cfg.setTime(System.currentTimeMillis());
			LockScreenConfig.setLockscreenConfig(this, cfg);
			List<LockscreenCfgItem> list = cfg.getConfig();
			if (list == null) {
				return;
			}
			for (LockscreenCfgItem item : list) {
				String iconN = item.getLinkIconNormal();
				String iconP = item.getLinkIconPressed();
				String iconS = item.getLinkIconSelected();
				String image = item.getImage();
				// 下载需要的图片，不用担心同步问题，ImageLoader线程有重入锁
				DisplayImageOptions dio = new DisplayImageOptions.Builder().cacheInMemory(false).cacheOnDisk(true)
						.build();

				ImageLoader.getInstance().loadImage(iconN, dio, null);
				ImageLoader.getInstance().loadImage(iconP, dio, null);
				ImageLoader.getInstance().loadImage(iconS, dio, null);
				final NET_TYPE nt = NetTools.getNetworkType(this);

				if (NET_TYPE.TYPE_WIFI == nt || !LockScreenConfig.isWallpaperOfWifi(this)) {
					Calendar cal = Calendar.getInstance();
					final long today = cal.getTimeInMillis();
					cal.add(Calendar.DAY_OF_MONTH, -1);
					final long yesterday = cal.getTimeInMillis();
					// 不用每次都下,当天或者提前一天下载就可以
					if (DateUtils.isSameDay(today, cfg.getTime()) || DateUtils.isSameDay(yesterday, cfg.getTime())) {
						ImageLoader.getInstance().loadImage(image, null);
					}
				}

			}

		} else {
			WidgetResultData widgetResult = (WidgetResultData) result;
			if (tag == TOOL_WIDGET) {
				mToolRunning = false;
			} else if (tag == GAME_WIDGET) {
				mGameRunning = false;
			} else if (tag == ENTERTAINMENT_WIDGET) {
				mEntertainmentRunning = false;
			} else {
				LogUtil.w(TAG, "unknown tag:" + tag);
			}
			if (!widgetResult.isOK()) {
				try {
					LogUtil.w(TAG, "request widget error");
					String type = ((WidgetNetEngine) engine).getCommand();
					WidgetNetEngine.restoreCache(type);
					widgetResult = new WidgetResultData(type);
					WidgetCacheStrategy wcs = new WidgetCacheStrategy(type);

					widgetResult.parseResult(widgetResult.getFileContentString(wcs.getCacheFile()));

					updateWidgetIcon(widgetResult.getList(), tag - 1, false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				updateWidgetIcon(widgetResult.getList(), tag - 1, ((WidgetNetEngine) engine).isCacheExpired());
			}

		}
	}

	private String getCommand(int type) {
		String s = WidgetNetEngine.TYPE_TOOL;
		if (type == WidgetIconUtils.TYPE_GAME_WIDGET) {
			s = WidgetNetEngine.TYPE_GAME;
		} else if (type == WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET) {
			s = WidgetNetEngine.TYPE_ENTERTAINMENT;
		}
		return s;
	}

	@Override
	public void onTaskRunError(int tag) {
		Log.e(TAG, "onTaskRunError:" + tag);
		if (tag == PHONE_ESSENTIAL) {
			mPhoneEssentialRunning = false;
		} else if (tag == TOOL_WIDGET) {
			mGameRunning = false;
		} else if (tag == GAME_WIDGET) {
			mPhoneEssentialRunning = false;
		} else if (tag == ENTERTAINMENT_WIDGET) {
			mEntertainmentRunning = false;
		}

		if (tag == TOOL_WIDGET || tag == GAME_WIDGET || tag == ENTERTAINMENT_WIDGET) {
			try {
				LogUtil.w(TAG, "request widget error");
				String type = getCommand(tag - 1);
				WidgetNetEngine.restoreCache(type);
				WidgetResultData widgetResult = new WidgetResultData(type);
				WidgetCacheStrategy wcs = new WidgetCacheStrategy(type);
				widgetResult.parseResult(widgetResult.getFileContentString(wcs.getCacheFile()));
				updateWidgetIcon(widgetResult.getList(), tag - 1, widgetResult.getGroup() == 0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void onTaskRunCanceled(int tag) {
		// no way go to here
	}

	@Override
	public void onDestroy() {
		NetTask[] tasks = new NetTask[4];
		tasks[0] = mPhoneEssentialTask;
		tasks[1] = mToolWidgetTask;
		tasks[2] = mGameWidgetTask;
		tasks[3] = mEntertainmentWidgetTask;

		for (NetTask t : tasks) {
			if (t != null) {
				t.setListener(null);
				t.cancel();
				t = null;
			}
		}
	}

	public static void startPollService(Context context) {
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, PollService.class);
		PendingIntent pIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, TIME, pIntent);
	}

	public static boolean isServiceRunning(Context context) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(100);
		if (serviceList.size() == 0) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(PollService.class.getName())) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

}
